package main

import (
	"../../backend"
	"../../mysql"
	"fmt"
)

func main() {

	addr := "172.16.50.188:4410"
	user := "mysqlsync"
	pass := "mysqlsync"

	c := newConn(addr, user, pass)

	// Only for MySQL > 5.6
	_, err := c.Execute("set @master_binlog_checksum= @@global.binlog_checksum")
	if err != nil {
		fmt.Println(err)
	}

	binlogFileV, binlogPosV, err := c.ShowMasterStatus("show master status")
	if err != nil {
		panic(err)
	}

	binlogFile := []byte(binlogFileV)
	var binlogFlag uint16 = 0
	var serverId uint32 = 698148981

	length := len(binlogFile)
	data := make([]byte, 1+4+2+4+length)

	data[0] = mysql.COM_BINLOG_DUMP

	data[1] = byte(binlogPosV & 0xFFFFFFFF) // binlogPosV & 0xFFFFFFFF  uint64 --> uint32
	data[2] = byte((binlogPosV & 0xFFFFFFFF) >> 8)
	data[3] = byte((binlogPosV & 0xFFFFFFFF) >> 16)
	data[4] = byte((binlogPosV & 0xFFFFFFFF) >> 24)

	data[5] = byte(binlogFlag)
	data[6] = byte(binlogFlag >> 8)

	data[7] = byte(serverId)
	data[8] = byte(serverId >> 8)
	data[9] = byte(serverId >> 16)
	data[10] = byte(serverId >> 24)

	copy(data[1+4+2+4:], binlogFile)

	c.BinlogDump(data, addr, user, pass)
}

func newConn(addr string, user string, pass string) *backend.Conn {
	c := new(backend.Conn)

	if err := c.Connect(addr, user, pass, ""); err != nil {
		fmt.Println("Connect failed ____________________")
	} else {
		fmt.Println("Connect success ____________________")
	}

	return c
}
